package tech.xyxy.channeltest.channelpkgtest;

import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.WalleChannelReader;

import java.util.Map;

/**
 * 使用美团walle
 * https://github.com/Meituan-Dianping/walle
 */
public class MainActivity extends AppCompatActivity {
    WebView webview;
    static String TAG = "CHANNEL_PKG_TEST";
    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);
        String url = "http://192.168.0.55:8080/";
        setContentView(R.layout.activity_main);
        webview = findViewById(R.id.webview);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            webview.getSettings().setSafeBrowsingEnabled(false);
        }

        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading( WebView view, WebResourceRequest request ) {
                return false;
            }

            @Override
            public void onPageFinished( WebView view, String url ) {
                super.onPageFinished(view, url);
            }
        });
        ChannelInfo channelInfo= WalleChannelReader.getChannelInfo(this.getApplicationContext());
        String params = "";
        if (channelInfo != null) {
            String channel = channelInfo.getChannel();
            Map<String, String> extraInfo = channelInfo.getExtraInfo();
            Log.i(TAG,extraInfo.toString());
            params = makeParam(extraInfo);
        }
        webview.loadUrl(url+params);
    }
    String makeParam(Map<String,String> data){
        String tmp = "?";
        int i = 0;
        for (Map.Entry<String, String> entry : data.entrySet()) {
            Log.i(TAG,"Key = " + entry.getKey() + ", Value = " + entry.getValue());

            tmp+=(entry.getKey()+"="+entry.getValue());
            if(i<data.size())
                tmp+="&";
            i++;
        }
        return tmp;
    }
}
